unit AppExistSpy;
interface

{$mode Delphi}

uses
  Windows, KOL;

function SpyEnable(Form: PControl): Boolean;

implementation

const
  WM_EXISTS = 1024 + 1;
  EventName = 'App_Already_Exists_Event';

var
  Event: THandle;
  OldWndProc: WndProc;
  MainForm: PControl;
  WaitThread: PThread;

function NewWndProc(hWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; StdCall;
begin
  if msg = WM_EXISTS then
  begin
    ShowWindow(MainForm^.Handle, SW_RESTORE);
  end
  else
    result := CallWindowProc(OldWndProc, hWnd, Msg, wParam, lParam);
end;

function OnExecute(Self: PObj; Sender:PThread): Integer;
begin
  while True do
  begin
    if WaitForSingleObject(Event, INFINITE) <> WAIT_OBJECT_0 then
      Exit;
    SendMessage(MainForm^.Handle, WM_EXISTS, 0, 0);
  end;
end;

function SpyEnable(Form: PControl): boolean;
var
  Proc: TOnThreadExecute;
begin
  Proc := TOnThreadExecute(MakeMethod(nil, @onexecute));
  result := true;
  MainForm := Form;
  OldWndProc := WndProc(SetWindowLong(Form^.Handle, GWL_WNDPROC, LongInt(@NewWndProc)));
  Event := CreateEvent(nil, False, False, EventName);
  if GetLastError = ERROR_ALREADY_EXISTS then
  begin
    Event := OpenEvent(EVENT_MODIFY_STATE, False, EventName);
    result := false;
    SetEvent(Event);
    CloseHandle(Event);
  end else WaitThread := NewThreadEx(proc);
end;


end.
